package com.lc.boxuegu.M_levelOrder;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

/**
 * @author zhaiyj
 * @date 2025/6/15 20:28
 */
public class Solution {


    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
//            return List.of();
            return new ArrayList<>();
        }
        List<List<Integer>> ans = new ArrayList<>();
        Queue<TreeNode> q = new ArrayDeque<>();
        q.add(root);
        while (!q.isEmpty()) {
            int n = q.size();
            List<Integer> vals = new ArrayList<>(n); // 预分配空间
            while (n-- > 0) {
                TreeNode node = q.poll();
                vals.add(node.val);
                if (node.left != null)  q.add(node.left);
                if (node.right != null) q.add(node.right);
            }
            ans.add(vals);
        }
        return ans;
    }

    public List<List<Integer>> levelOrder1(TreeNode root) {
        if (root == null) {
//            return List.of();
            return new ArrayList<>();
        }

        List<List<Integer>> ans = new ArrayList<>();
//        List<TreeNode> cur = List.of(root);
        List<TreeNode> cur = null;
        while (!cur.isEmpty()) {
            List<TreeNode> nxt = new ArrayList<>();
            List<Integer> vals = new ArrayList<>(cur.size());

            for (TreeNode treeNode : cur) {
                vals.add(treeNode.val);
                if (treeNode.left != null) {
                    nxt.add(treeNode.left);
                }
                if (treeNode.right != null) {
                    nxt.add(treeNode.right);
                }
            }
            cur = nxt;
            ans.add(vals);
        }
        return ans;
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


}
